package com.lemon.exam.common.config;

import com.lemon.exam.common.enums.RouteEnum;
import com.lemon.exam.common.exception.CustomException;
import com.lemon.exam.common.handler.RouterFunctionHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.*;

import java.util.Arrays;

/**
 * 路由配置
 *
 * @author Lemon
 * @since 2025/4/2 11:38
 */
@Slf4j
@Configuration
public class RouterConfiguration {
    /**
     * 路由配置
     *
     * @param handler 路由处理类
     * @return
     */
    @Bean
    public RouterFunction<ServerResponse> routers(RouterFunctionHandler handler) {
        return Arrays.stream(RouteEnum.values())
                .map(route -> RouterFunctions.route(createPredicate(route), route.getHandlerFunction().apply(handler)))
                .reduce(RouterFunction::and)
                .orElseThrow(() -> new CustomException("无法创建路由"));
    }

    /**
     * 创建请求方式匹配器
     *
     * @param route 路由枚举对象
     * @return
     */
    private static RequestPredicate createPredicate(RouteEnum route) {
        return switch (route.getMethod().name()) {
            case "GET" -> RequestPredicates.GET(route.getPath());
            case "POST" -> RequestPredicates.POST(route.getPath());
            case "PUT" -> RequestPredicates.PUT(route.getPath());
            case "DELETE" -> RequestPredicates.DELETE(route.getPath());
            case "PATCH" -> RequestPredicates.PATCH(route.getPath());
            case "OPTIONS" -> RequestPredicates.OPTIONS(route.getPath());
            case "HEAD" -> RequestPredicates.HEAD(route.getPath());
            default -> throw new CustomException("不支持的HTTP方法: " + route.getMethod());
        };
    }
}
